using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using UniversalAdmin.Api.Models;
using UniversalAdmin.Application.DTOs;
using UniversalAdmin.Domain.Interfaces;
using UniversalAdmin.Domain.Repositories;

namespace UniversalAdmin.Api.Controllers;

[ApiController]
[Route("api/system-configs")]
// [Authorize("admin.system.manage")] // 临时注释掉权限验证，用于测试
public class SystemConfigsController : ControllerBase
{
  private readonly ISystemConfigRepository _repo;
  private readonly IUnitOfWork _uow;

  public SystemConfigsController(ISystemConfigRepository repo, IUnitOfWork uow)
  {
    _repo = repo;
    _uow = uow;
  }

  ///<summary>
  /// 获取所有配置
  ///</summary>
  [HttpGet]
  public async Task<IActionResult> GetAll()
  {
    var configs = await _repo.GetAllAsync();
    var dtos = configs.Select(c => new SystemConfigDto
    {
      Id = c.Id,
      Key = c.Key,
      Value = c.Value,
      Description = c.Description,
      CreatedAt = c.CreatedAt,
      UpdatedAt = c.UpdatedAt
    });
    return Ok(ApiResponse<IEnumerable<SystemConfigDto>>.Success(dtos));
  }

  ///<summary>
  /// 更新配置
  ///</summary>
  [HttpPut("{id:int}")]
  public async Task<IActionResult> Update(int id, [FromBody] UpdateSystemConfigDto dto)
  {
    var config = await _repo.GetByIdAsync(id);
    if (config == null) return NotFound(ApiResponse.Error(404, "配置不存在"));

    config.Value = dto.Value;
    config.Description = dto.Description;
    config.UpdatedAt = DateTime.UtcNow;

    await _repo.UpdateAsync(config);
    await _uow.SaveChangesAsync();

    // 记录日志
    await LogAsync("SystemConfig.Update", "system_configs", config.Id);

    return Ok(ApiResponse.Success("配置已更新"));
  }

  ///<summary>
  /// 批量更新配置
  ///</summary>
  [HttpPut("batch")]
  public async Task<IActionResult> BatchUpdate([FromBody] IEnumerable<BatchUpdateSystemConfigDto> dtos)
  {
    var configIds = dtos.Select(d => d.Id).ToList();
    var configs = await _repo.GetByIdsAsync(configIds);
    
    foreach (var dto in dtos)
    {
      var config = configs.FirstOrDefault(c => c.Id == dto.Id);
      if (config != null)
      {
        config.Value = dto.Value;
        config.UpdatedAt = DateTime.UtcNow;
      }
    }

    await _repo.UpdateRangeAsync(configs);
    await _uow.SaveChangesAsync();

    // 记录日志
    await LogAsync("SystemConfig.BatchUpdate", "system_configs", null);

    return Ok(ApiResponse.Success("配置已批量更新"));
  }

  private async Task LogAsync(string action, string resource, int? resourceId)
  {
    var log = new Domain.Entities.OperationLog
    {
      UserId = int.Parse(User.FindFirst(System.Security.Claims.ClaimTypes.NameIdentifier)!.Value),
      Action = action,
      Resource = resource,
      ResourceId = resourceId,
      IpAddress = GetClientIpAddress(),
      UserAgent = Request.Headers.UserAgent
    };
    await _uow.OperationLogRepository.AddAsync(log);
    await _uow.SaveChangesAsync();
  }

  private string GetClientIpAddress()
  {
    // 首先检查代理头（如果通过反向代理）
    var forwardedFor = Request.Headers["X-Forwarded-For"].FirstOrDefault();
    if (!string.IsNullOrEmpty(forwardedFor))
    {
      // X-Forwarded-For 可能包含多个IP，取第一个
      var ip = forwardedFor.Split(',')[0].Trim();
      if (!string.IsNullOrEmpty(ip))
        return ip;
    }

    // 检查 X-Real-IP 头
    var realIp = Request.Headers["X-Real-IP"].FirstOrDefault();
    if (!string.IsNullOrEmpty(realIp))
      return realIp;

    // 获取远程IP地址
    var remoteIp = HttpContext.Connection.RemoteIpAddress;
    if (remoteIp != null)
    {
      // 如果是IPv6的本地环回地址，转换为IPv4
      if (remoteIp.ToString() == "::1")
        return "127.0.0.1";
      
      // 如果是IPv6地址，但不是本地环回，保持原样
      return remoteIp.ToString();
    }

    return "Unknown";
  }
}